<template>
  <div class="booking-form">
    <div class="form-header">
      <h3>预订信息</h3>
    </div>
    
    <a-form :model="formState" @finish="handleSubmit" layout="vertical">
      <!-- Date Selection -->
      <a-form-item label="入住日期" name="dates" :rules="[{ required: true, message: '请选择入住日期' }]">
        <a-range-picker
          v-model:value="formState.dates"
          :disabled-date="disabledDate"
          format="YYYY-MM-DD"
          :placeholder="['入住日期', '退房日期']"
          size="large"
          style="width: 100%"
          :bordered="true"
        />
      </a-form-item>

      <!-- Guest Count -->
      <a-form-item label="入住人数" name="guestCount" :rules="[{ required: true, message: '请选择入住人数' }]">
        <a-input-number
          v-model:value="formState.guestCount"
          :min="1"
          :max="maxGuests"
          size="large"
          style="width: 100%"
          :bordered="true"
        />
      </a-form-item>

      <!-- Traveler Selection -->
      <a-form-item label="入住旅客" name="travelers" :rules="[{ required: true, message: '请选择入住旅客' }]">
        <a-select
          v-model:value="formState.travelers"
          mode="multiple"
          placeholder="选择入住旅客"
          :options="travelerOptions"
          @change="handleTravelerChange"
          size="large"
          style="width: 100%"
          :bordered="true"
        >
          <template #footer>
            <a-button type="link" block @click="showAddTravelerModal">
              <user-add-outlined /> 添加新旅客
            </a-button>
          </template>
        </a-select>
      </a-form-item>
      
      <!-- Add Traveler Button -->
      <a-form-item>
        <a-button type="dashed" block @click="showAddTravelerModal" style="margin-top: -15px">
          <user-add-outlined /> 添加新旅客
        </a-button>
      </a-form-item>

      <!-- Price Summary -->
      <div class="price-summary">
        <div class="price-item">
          <span>房间单价</span>
          <span>¥{{ roomPrice }}/晚</span>
        </div>
        <div class="price-item">
          <span>入住天数</span>
          <span>{{ nightCount }}晚</span>
        </div>
        <div class="price-item total">
          <span>总价</span>
          <span class="total-price">¥{{ totalPrice }}</span>
        </div>
      </div>

      <!-- Submit Button -->
      <a-form-item>
        <a-button type="primary" html-type="submit" :loading="loading" block size="large">
          <check-circle-outlined /> 确认预订
        </a-button>
      </a-form-item>
    </a-form>

    <!-- Add Traveler Modal -->
    <a-modal
      v-model:visible="addTravelerVisible"
      title="添加旅客"
      @ok="handleAddTraveler"
      :confirmLoading="addTravelerLoading"
      class="traveler-modal"
    >
      <a-form :model="newTraveler" layout="vertical">
        <a-form-item label="姓名" name="name" :rules="[{ required: true, message: '请输入姓名' }]">
          <a-input v-model:value="newTraveler.name" placeholder="请输入姓名" />
        </a-form-item>
        <a-form-item label="身份证号" name="idCard" :rules="[{ required: true, message: '请输入身份证号' }]">
          <a-input v-model:value="newTraveler.idCard" placeholder="请输入身份证号" />
        </a-form-item>
        <a-form-item label="手机号" name="phone" :rules="[{ required: true, message: '请输入手机号' }]">
          <a-input v-model:value="newTraveler.phone" placeholder="请输入手机号" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { 
  UserAddOutlined, 
  CheckCircleOutlined 
} from '@ant-design/icons-vue'
import { apiGetTravelers, apiAddTraveler, apiCreateBooking } from '@/api/api'
import { useRouter } from 'vue-router'
import { log } from 'echarts/types/src/util/log.js'
const router = useRouter()
const props = defineProps<{
  roomId: number
  hotelId: string | number
  roomPrice: number
  maxGuests: number  
}>()

const emit = defineEmits(['booking-success'])

const formState = ref<{
  dates: [dayjs.Dayjs, dayjs.Dayjs];
  guestCount: number;
  travelers: any[];
}>({
  dates: [dayjs(), dayjs().add(1, 'day')],
  guestCount: 1,
  travelers: []
})

const loading = ref(false)
const travelerOptions = ref<{label: string, value: any, phone?: string}[]>([])
const addTravelerVisible = ref(false)
const addTravelerLoading = ref(false)
const newTraveler = ref({
  name: '',
  idCard: '',
  phone: ''
})

// Computed properties
const nightCount = computed(() => {
  if (!formState.value.dates || formState.value.dates.length !== 2) return 0
  return formState.value.dates[1].diff(formState.value.dates[0], 'day')
})

const totalPrice = computed(() => {
  return props.roomPrice * nightCount.value
})

// Methods
const disabledDate = (current: dayjs.Dayjs) => {
  return current && current < dayjs().startOf('day')
}

const loadTravelers = async () => {
  try {
    const response = await apiGetTravelers()
    travelerOptions.value = response.data.map((traveler: any) => ({
      label: `${traveler.name} (${traveler.idCard})`,
      value: traveler.id,
      phone: traveler.phone // 保存电话号码
    }))
  } catch (error) {
    message.error('获取旅客信息失败')
  }
}

const handleTravelerChange = (values: any[]) => {
  formState.value.travelers = values
}

const handleAddTraveler = async () => {
  if (!newTraveler.value.name || !newTraveler.value.idCard || !newTraveler.value.phone) {
    message.error('请填写完整的旅客信息')
    return
  }
  
  try {
    addTravelerLoading.value = true
    const res: any = await apiAddTraveler(newTraveler.value)
    if(res && res.code === 200) {
    message.success('添加旅客成功')
      addTravelerVisible.value = false
      await loadTravelers()
      newTraveler.value = { name: '', idCard: '', phone: '' }
    } else {
      message.error(res.msg || '添加旅客失败')
    }
  } catch (error) {
    message.error('添加旅客失败')
  } finally {
    addTravelerLoading.value = false
  }
}

const showAddTravelerModal = () => {
  addTravelerVisible.value = true
}

const handleSubmit = async () => {
  if (formState.value.travelers.length === 0) {
    message.warning('请至少选择一位入住旅客')
    return
  }
  
  try {
    loading.value = true
    
    // 将旅客ID转换为所需的格式
    const travelersData = formState.value.travelers.map((travelerId: any) => {
      const traveler = travelerOptions.value.find((option: any) => option.value === travelerId)
      if (traveler) {
        // 从label中提取name和idCard
        // 格式为 "姓名 (身份证号)"
        console.log("traveler", traveler)
        const match = traveler.label.match(/^(.+) \((.+)\)$/)
        if (match) {
          return {
            name: match[1],
            idCard: match[2],
            phone: traveler.phone // 添加电话号码
          }
        }
      }
      return null
    }).filter(Boolean) as { name: string, idCard: string, phone: string }[]
    
  
 
    
    const bookingData = {
      hotelId: props.hotelId,
      roomId: props.roomId,
      checkIn: formState.value.dates[0].format('YYYY-MM-DD'),
      checkOut: formState.value.dates[1].format('YYYY-MM-DD'),
      guestCount: formState.value.guestCount,
      travelers: travelersData,
      totalPrice: totalPrice.value
    }

    const res: any = await apiCreateBooking(bookingData)
    // 返回创建成功的订单号
    if(res && res.code === 200) {
      const bookingId = res.data
      message.success('预订成功，即将跳转到支付页面')
      
      // 创建支付请求 - 修改为直接跳转页面方式
      window.location.href = `http://localhost:8080/payment/create/${bookingId}`
      
      emit('booking-success')
    } else {
      message.error(res.msg || '预订失败，请重试')
    }
  } catch (error) {
    console.log(error)
    message.error('预订失败，请重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadTravelers()
})
</script>

<style scoped>
.booking-form {
  padding: 0;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.06);
  transition: all 0.3s ease;
}

.booking-form:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}

.form-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.form-header h3 {
  margin: 0;
  font-size: 18px;
  color: #262626;
  font-weight: 600;
}

a-form {
  padding: 24px;
}

:deep(.ant-form-item-label) {
  padding-bottom: 8px;
}

:deep(.ant-form-item-label > label) {
  color: #262626;
  font-weight: 500;
}

:deep(.ant-input-number),
:deep(.ant-picker),
:deep(.ant-select-selector) {
  border-radius: 6px !important;
}

.price-summary {
  margin: 24px 0;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 8px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  color: #595959;
}

.price-item.total {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
  font-weight: bold;
  font-size: 16px;
  color: #262626;
}

.total-price {
  font-size: 20px;
  color: #f5222d;
}

:deep(.ant-btn-primary) {
  height: 48px;
  font-size: 16px;
  border-radius: 6px;
}

:deep(.ant-btn-primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
}

.traveler-modal {
  :deep(.ant-modal-content) {
    border-radius: 12px;
  }
}

@media (max-width: 576px) {
  .booking-form {
    border-radius: 0;
    box-shadow: none;
  }
}
</style> 